package com.goa.core;

import com.goa.entity.DeviceCron;
import com.goa.parse.HexToByteArray;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * TCP发送数据
 */
@Slf4j
@Component
public class SessionTrackingHandler extends ChannelInboundHandlerAdapter {


    private SessionTrackingHandler sessionTrackingHandler;

    // 假设你有一个方法来获取或设置SessionTrackingHandler实例
    // 这通常需要在Netty服务器启动时设置
    public void setSessionTrackingHandler(SessionTrackingHandler handler) {
        this.sessionTrackingHandler = handler;
    }

    /**
     * TCP发送指令
     *
     * @param channel 客户端连接对象
     * @param command       发送指令编码
     * @param jobEntity     定时任务对象（基础信息）
     */

    public void sendCommandToClient(Channel channel, String command, DeviceCron jobEntity) {
//        Channel channel = SessionMap.clientSessions.get(clientAddress);
        if (channel != null && channel.isActive()) {
            // 创建ByteBuf来保存要发送的数据
            //1-2 设备ID和定时任务表的主键
            String requestId = jobEntity.getId() + "-" + jobEntity.getDeviceId();
            channel.attr(AttributeKey.valueOf("requestId")).set(requestId);
            //发送数据
            byte[] bytes1 = HexToByteArray.toByteArray(command);
            ByteBuf buffer = channel.alloc().buffer();
            boolean released = false;
            try {
                buffer.writeBytes(bytes1);
                ChannelFuture channelFuture = channel.writeAndFlush(buffer);
                channelFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (future.isSuccess()) {
                            log.info("消息发送成功, 发送的指令是 " + command);
                            // 等待响应
                            try {
                            } catch (Exception e) {
                                Thread.currentThread().interrupt(); // 恢复中断状态
                                log.error("等待响应时被中断: " + e.getMessage());
                            }
                        } else {
                            // 消息发送失败
                            Throwable cause = future.cause();
                            log.error("消息发送失败: " + cause.getMessage());
                        }
                    }
                });

                released = true; // 标记为已释放
            } finally {
                if (!released) {
                    ReferenceCountUtil.release(buffer); // 如果没有在listener里释放，则手动释放
                }
            }
        } else {
            log.info("无法向客户端 " + channel.remoteAddress() + " 发送指令，因为连接不存在或已关闭");
        }

    }

}